# -*- coding:utf-8 -*-

from flask import request, session
from app.models.log import StaffLog
from app import db
import datetime
import urllib2
import json
from config import Config


def log(operation):
	data = {}
	data['ip'] = session.get('ip', u'未知')
	data['name'] = session.get('name', u'未知')
	data['staff_number'] = session.get('staff_number', u'未知')
	data['time'] = datetime.datetime.now()
	data['operation'] = operation
	data['area'] = session.get('area', u'未知')
	db.session.add(StaffLog(**data))
	db.session.commit()
	return 0
	
def get_city_by_ip(ip):
	try:
		response = urllib2.urlopen('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s' % ip)
		result = response.read()
		result = json.loads(result)
		if result == -2:
			return u'未知'
		city = result['city']
		return city
	except (urllib2.HTTPError, urllib2.URLError) as e:
		return ''
